//index.js
//获取应用实例
const app = getApp()
var util =  require('../../utils/util.js');
var json =  require('../../data/json.js');
var btnFlag = false
Page({
  data: {
    themeColor: app.globalData.themeColor,
    riceType: 1,
    dateType: 0,
    contentId: '',
    userId: '',
    status: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      date: util.setTime(new Date())
    })
  },

  //获取数据
  getData:function(){
    var that = this
    console.log(that.data.userId)
    let data = {
      date: that.data.date,
      user_id: that.data.userId,
      date_type: that.data.dateType
    }
    data = JSON.stringify(data)
    util.getAjax(app.globalData.apiUrl +'/Api/Food/get_user_food_order',function(res){
      console.log(res)
      if(res.data != 0){
        that.setData({
          isOrderMeal: true,
          noteTxt: that.getType(res.data.type)
        })
      }
    },{pro: data})
  },

  //获取食物
  getfood:function(){
    var that = this;
    let id = new Date().getDay();
    if(id == 0) id=7;
      // console.log(id);
      //获取商品详情
    util.getAjax(app.globalData.apiUrl +'/Api/Food/get_food',function(res){
      console.log(res)
      if(res.data[0].content.length != 0){
        if(res.data[0].content){
          var content = []
          var reg = /(\s+)?(\s+|，|,)(\s*|，|,)?/g
          res.data[0].content = res.data[0].content.replace(reg,',');
          res.data[0].content = res.data[0].content.substr(res.data[0].content.length - 1,1) == ','?res.data[0].content.slice(0,res.data[0].content.length-1):res.data[0].content
          content = res.data[0].content.split(',')
        }
        that.setData({
          isMenu: true,
          content: content,
          week: res.data[0].id,
        })
      }
    },{id: id})
  },

  //获取状态
  getType:function(type){
    var text =''
    var dateType = this.data.dateType == 1?'午餐':'晚餐'
    var note = '已预订：'
    switch (type) {
      case '1':
        text = dateType + note + '常规餐'
        break;
      case '2':
        text = dateType + note + '清真餐'
        break;
      case '3':
        text = dateType + note + '全素餐'
        break;
    }
    return text
  },

  //获取状态
  getRiceType:function(type){
    var text =''
    switch (type) {
      case '1':
        text = '需要主食'
        break;
      case '2':
        text = '不需要主食'
        break;
    }
    return text
  },

  radioChange:function(e){
    // console.log(e)
    this.setData({
      riceType: e.detail.value
    })
  },
  //订餐按钮
  OrderMealBtn:function(e){
    var that = this
    if(btnFlag){
      return
    }
    btnFlag = true
    if(that.data.dateType == 0){
      util.showToast('未在定餐时间，或请重试','none',2000)
      btnFlag = false
      return;
    }
    var type = e.currentTarget.dataset.type
    if(that.data.status && that.data.status == 1 && that.data.userId && that.data.contentId){
      let data = {
        date: that.data.date,
        type: type,
        rice_type: that.data.riceType,
        user_id: that.data.userId,
        content_id: that.data.contentId,
        date_type: that.data.dateType
      }
      data = JSON.stringify(data)
      // console.log(data)
      util.postAjax(app.globalData.apiUrl +'/Api/Food/yes_food',function(res){
        console.log(res)
        if(res.data == '1'){
          //成功
          that.setData({
            isOrderMeal: true
          })
          let text = '您' + that.getType(type) + '并' + that.getRiceType(that.data.riceType) + '成功'
          util.showToast(text,'none',2000)
          that.getData()
        }else{
          //失败
          util.showModal('提示','订餐失败，请重试')
        }
        btnFlag = false
      },{id: '',date: that.data.date,pro: data})
    }else{
      wx.login({
        success:function(login){
          // 发送请求
          wx.request({
            url: app.globalData.apiUrl + '/Api/GetUser/get_openid', //接口地址
            data: {
              code: login.code,
            },
            method: 'get',
            header: {
              'content-type': 'application/json' //默认值
            },
            success: function (res) {
              console.log(res)
              //判断用户是否存在
              if(res.data.code == '1'){
                app.globalData.userId = res.data.data.id;
                app.globalData.contentId = res.data.data.content_id;
                app.globalData.status = res.data.data.status;
                if(res.data.data.is_manager){
                  app.globalData.isManager = res.data.data.is_manager
                }
                if(res.data.data.status == 1){
                  //后台有数据
                  let data = {
                    date: that.data.date,
                    type: type,
                    user_id: res.data.data.id,
                    rice_type: that.data.riceType,
                    content_id: res.data.data.content_id,
                    date_type: that.data.dateType
                  }
                  data = JSON.stringify(data)
                  // console.log(data)
                  util.postAjax(app.globalData.apiUrl +'/Api/Food/yes_food',function(res){
                    console.log(res)
                    if(res.data == '1'){
                      //成功
                      that.setData({
                        isOrderMeal: true
                      })
                      let text = '您' + that.getType(type) + '并' + that.getRiceType(that.data.riceType) + '成功'
                      util.showToast(text,'none',2000)
                      that.getData()
                    }else{
                      //失败
                      util.showModal('提示','订餐失败，请重试')
                    }
                    btnFlag = false
                  },{id: '',date: that.data.date,pro: data})
                }else{
                  util.showToast('您还未通过审核，暂不能定餐','none',2000),
                  btnFlag = false
                }
              }
            }
          })
        }
      })
    }
  },

  //更改
  btnClick:function(){
    wx.navigateTo({
      url: '../mineRecord/mineRecord',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    that.getfood();
    if(app.globalData.mainTime.length != 0){
      let dateType = 0
      for(let i in app.globalData.mainTime){
        let isDate = util.setDate(app.globalData.mainTime[i].food_time,app.globalData.mainTime[i].food_end_time)
        if(isDate){
          dateType = Number(app.globalData.mainTime[i].id)
          break;
        }
      }
      that.setData({
        mainTime: app.globalData.mainTime,
        dateType: Number(dateType)
      })
    }else{
      app.mainTimeCallback = mainTime => {
        if (mainTime != '') {
          let dateType = 0
          for(let i in mainTime){
            let isDate = util.setDate(mainTime[i].food_time,mainTime[i].food_end_time)
            if(isDate){
              dateType = Number(mainTime[i].id)
              break;
            }
          }
          that.setData({
            mainTime: mainTime,
            dateType: Number(dateType)
          })
        }
      }
    }
    if(app.globalData.userId){
      that.setData({
        userId: app.globalData.userId
      })
      that.getData();
    }else{
      app.userIdCallback = userId => {
        if (userId != '') {
          that.setData({
            userId: userId
          });
          that.getData();
        }
      }
    }
    if(app.globalData.contentId){
      that.setData({
        contentId: app.globalData.contentId
      })
    }else{
      app.contentIdCallback = contentId => {
        if (contentId != '') {
          that.setData({
            contentId: contentId
          });
        }
      }
    }
    if(app.globalData.status){
      that.setData({
        status: app.globalData.status
      })
    }else{
      app.statusCallback = status => {
        if (status != '') {
          that.setData({
            status: status
          });
        }
      }
    }
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }

})
